"""
输入框组件模块

提供了一个美观、功能丰富的输入框组件，支持标签、占位文本、验证、清除按钮等功能。
"""
from PyQt5.QtWidgets import (QWidget, QLineEdit, QLabel, QHBoxLayout, 
                            QVBoxLayout, QPushButton, QApplication, QSizePolicy)
from PyQt5.QtCore import Qt, pyqtSignal, QSize
from PyQt5.QtGui import QIcon, QPixmap, QPainter, QColor

from .theme import Theme


class Input(QWidget):
    """
    输入框组件
    
    用法:
        input = Input(label="用户名", placeholder="请输入用户名")
        input.textChanged.connect(self.on_text_changed)
        layout.addWidget(input)
    """
    
    # 自定义信号
    textChanged = pyqtSignal(str)
    textEdited = pyqtSignal(str)
    returnPressed = pyqtSignal()
    
    def __init__(self, parent=None, label="", placeholder="", password_mode=False, 
                 clearable=True, disabled=False, readonly=False, max_length=None):
        """
        初始化输入框组件
        
        参数:
            parent: 父组件
            label: 标签文本
            placeholder: 占位文本
            password_mode: 是否为密码输入模式
            clearable: 是否显示清除按钮
            disabled: 是否禁用
            readonly: 是否只读
            max_length: 最大输入长度
        """
        super().__init__(parent)
        
        # 保存参数
        self.label_text = label
        self.placeholder = placeholder
        self.clearable = clearable
        
        # 创建主布局
        self.main_layout = QVBoxLayout(self)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(5)
        
        # 创建标签（如果提供）
        if label:
            self.label = QLabel(label)
            self.label.setObjectName("input-label")
            self.main_layout.addWidget(self.label)
        
        # 创建输入框容器
        self.input_container = QWidget()
        self.input_container.setObjectName("input-container")
        self.input_container.setMinimumHeight(36)
        
        # 设置容器的大小策略
        self.input_container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        # 输入框容器布局
        self.container_layout = QHBoxLayout(self.input_container)
        self.container_layout.setContentsMargins(10, 0, 10, 0)
        self.container_layout.setSpacing(0)  # 减少间距
        
        # 创建输入框
        self.line_edit = QLineEdit()
        self.line_edit.setObjectName("input-field")
        self.line_edit.setPlaceholderText(placeholder)
        self.line_edit.setClearButtonEnabled(False)  # 我们将使用自定义清除按钮
        self.line_edit.setMinimumHeight(34)
        
        # 设置大小策略，允许水平方向收缩
        self.line_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        # 设置密码模式
        if password_mode:
            self.line_edit.setEchoMode(QLineEdit.Password)
        
        # 设置最大长度
        if max_length is not None:
            self.line_edit.setMaxLength(max_length)
        
        # 设置禁用状态
        if disabled:
            self.line_edit.setEnabled(False)
        
        # 设置只读状态
        if readonly:
            self.line_edit.setReadOnly(True)
        
        # 连接信号
        self.line_edit.textChanged.connect(self._on_text_changed)
        self.line_edit.textEdited.connect(self._on_text_edited)
        self.line_edit.returnPressed.connect(self._on_return_pressed)
        
        # 添加输入框到容器
        self.container_layout.addWidget(self.line_edit, 1)  # 设置拉伸因子为1
        
        # 创建清除按钮（如果启用）
        if clearable:
            self.clear_button = QPushButton()
            self.clear_button.setObjectName("input-clear-button")
            self.clear_button.setFixedSize(24, 24)  # 增加按钮大小
            self.clear_button.setCursor(Qt.PointingHandCursor)
            self.clear_button.setIcon(self._create_clear_icon())
            self.clear_button.setIconSize(QSize(16, 16))  # 增加图标大小
            self.clear_button.clicked.connect(self.clear)
            self.clear_button.setVisible(False)  # 初始状态隐藏
            
            # 设置大小策略，固定大小
            self.clear_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            
            # 将清除按钮添加到容器布局
            self.container_layout.addWidget(self.clear_button, 0)  # 设置拉伸因子为0
        
        # 添加输入框容器到主布局
        self.main_layout.addWidget(self.input_container)
        
        # 设置整个组件的大小策略
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        # 应用样式
        self._apply_style()
    
    def _apply_style(self):
        """应用样式"""
        self.setStyleSheet(f"""
            QLabel#input-label {{
                color: {Theme.TEXT_PRIMARY};
                font-size: {Theme.FONT_SIZE_BASE}px;
                margin-bottom: 4px;
            }}
            
            QWidget#input-container {{
                background-color: {Theme.BG_COLOR};
                border: 1px solid {Theme.BORDER_LIGHT};
                border-radius: {Theme.BORDER_RADIUS_BASE}px;
            }}
            
            QWidget#input-container:focus-within {{
                border: 1px solid {Theme.PRIMARY};
            }}
            
            QLineEdit#input-field {{
                background-color: transparent;
                border: none;
                color: {Theme.TEXT_PRIMARY};
                font-size: {Theme.FONT_SIZE_BASE}px;
                selection-background-color: {Theme.PRIMARY_LIGHT};
            }}
            
            QLineEdit#input-field:disabled {{
                color: {Theme.TEXT_PLACEHOLDER};
                background-color: {Theme.BORDER_LIGHTER};
            }}
            
            QPushButton#input-clear-button {{
                background-color: transparent;
                border: none;
                color: {Theme.TEXT_SECONDARY};
                font-weight: bold;
                margin: 0;
                padding: 0;
            }}
            
            QPushButton#input-clear-button:hover {{
                background-color: {Theme.BG_COLOR_PAGE};
                border-radius: 12px;
            }}
        """)
    
    def _create_clear_icon(self):
        """创建清除图标"""
        pixmap = QPixmap(24, 24)
        pixmap.fill(Qt.transparent)
        
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 设置画笔
        pen = painter.pen()
        pen.setWidth(2)
        pen.setColor(QColor(Theme.TEXT_SECONDARY))
        painter.setPen(pen)
        
        # 绘制圆形背景
        painter.setBrush(QColor(Theme.BG_COLOR_PAGE))
        painter.drawEllipse(4, 4, 16, 16)
        
        # 绘制X形状
        painter.drawLine(8, 8, 16, 16)
        painter.drawLine(16, 8, 8, 16)
        
        painter.end()
        
        return QIcon(pixmap)
    
    def _on_text_changed(self, text):
        """文本变化处理"""
        # 更新清除按钮可见性
        if hasattr(self, 'clear_button'):
            self.clear_button.setVisible(bool(text) and self.clearable)
        
        # 发射信号
        self.textChanged.emit(text)
    
    def _on_text_edited(self, text):
        """文本编辑处理"""
        self.textEdited.emit(text)
    
    def _on_return_pressed(self):
        """回车键处理"""
        self.returnPressed.emit()
    
    def text(self):
        """获取文本"""
        return self.line_edit.text()
    
    def setText(self, text):
        """设置文本"""
        self.line_edit.setText(text)
    
    def clear(self):
        """清除文本"""
        self.line_edit.clear()
    
    def setPlaceholderText(self, text):
        """设置占位文本"""
        self.line_edit.setPlaceholderText(text)
    
    def setReadOnly(self, readonly):
        """设置只读状态"""
        self.line_edit.setReadOnly(readonly)
    
    def setEnabled(self, enabled):
        """设置启用状态"""
        self.line_edit.setEnabled(enabled)
        self.input_container.setEnabled(enabled)
    
    def setMaxLength(self, length):
        """设置最大长度"""
        self.line_edit.setMaxLength(length)
    
    def setEchoMode(self, mode):
        """设置回显模式"""
        self.line_edit.setEchoMode(mode)
    
    def setPasswordMode(self, password_mode):
        """设置密码模式"""
        if password_mode:
            self.line_edit.setEchoMode(QLineEdit.Password)
        else:
            self.line_edit.setEchoMode(QLineEdit.Normal)
    
    def setClearable(self, clearable):
        """设置是否可清除"""
        if hasattr(self, 'clear_button'):
            self.clearable = clearable
            # 如果有文本且可清除，则显示清除按钮
            self.clear_button.setVisible(bool(self.text()) and clearable) 